package file

import (
	"lifi"
	"lifi/plugins/sinks"
	"log"
	"os"
)

type File struct {
	Name string `json:"name,omitempty" yaml:"name"`
	Size int64  `json:"size,omitempty" yaml:"size"`
}

func (f File) Init() error {
	log.Printf("init file:%s", f.Name)
	return nil
}

func (f File) Close() error {
	return nil
}

func (f File) Connect() error {
	log.Printf("connect to sink file:%s", f.Name)

	_, err := os.Stat(f.Name)
	if err != nil {
		log.Printf("file [%s] not exist create it!", f.Name)
		_, err = os.Create(f.Name)
		if err != nil {
			log.Printf("create file [%s] error:%s", f.Name, err.Error())
			return err
		}
	}
	return nil
}

func (f File) Write(data ...lifi.Data) error {

	//dataPtr := unsafe.Pointer(&data[0].Data)
	// 使用unsafe.Slice将unsafe.Pointer转换为[]byte切片
	//dataSlice := unsafe.Slice((*byte)(dataPtr), packet.Length)

	dd, ok := data[0].(lifi.ByteData)
	if !ok {
		log.Printf("convert data to ByteData error, data:%s", dd.Data)
		return nil
	}

	err := os.WriteFile(f.Name, dd.Data, os.FileMode(0666))
	if err != nil {
		log.Printf("write file to file [%s]error:%s", f.Name, err.Error())
		return err
	}
	return nil
}

var _ lifi.Sink = File{}

func init() {
	sinks.Add("file", func() lifi.Sink {
		return &File{}
	})
}
